from fastapi import FastAPI, Request
import logging
import time
import os
from app.config import get_settings

def register_logger(app: FastAPI):
    settings = get_settings()

    today = time.strftime("%Y%m%d")
    #获取日志对象
    logger = logging.getLogger()
    #设置日志级别
    logger.setLevel(logging.DEBUG)
    #设置日志格式
    formatter = logging.Formatter("%(asctime)s - %(module)s - %(funcName)s - %(message)s")
    #设置文件
    path = settings.root_path+"/logs/server_"+today+".log"
    cf = logging.FileHandler(filename=path, mode="a", encoding="utf8")
    #应用格式
    cf.setFormatter(formatter)
    #设置日志
    logger.addHandler(cf)
    
    
    ## 定义日志中间件
    @app.middleware("http")
    async def log_middleware(req:Request, call_next):
        # 记录用户请求参数，请求结果
        # 记录请求时间
        today = time.strftime("%Y-%m-%d %H:%M:%S")
        today_short = time.strftime("%Y%m%d")

        start_time = time.time()

        #执行下一层操作
        resp = await call_next(req)

        #计算执行时间
        end_time = time.time()
        process_time = (end_time - start_time) * 1000

        flag = "正常"
        if process_time >= 1000 :
            #执行较慢
            flag = "慢接口"
        
        log = f"[{today}] - {req.client.host} - {req.method} - {req.url.path} - {resp.status_code} - [{req.headers.get('User-Agent')}] - 执行时间：{process_time} - {flag} \n"

        with open(settings.root_path+"/logs/access_"+today_short+".log", "a", encoding="utf8") as f:
            f.write(log)

        return resp

from functools import wraps
###############################################
#下面是用户行为日志注解
    
def Log(title: str, oper_type: str):
    #日志装饰器
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            settings = get_settings()
            
            result = func(*args, **kwargs)

            today = time.strftime("%Y-%m-%d %H:%M:%S")
            today_short = time.strftime("%Y%m%d")

            path = settings.root_path + "/logs/event_"+today_short+".log"

            log = f"[{today}] -  {title} - {oper_type} \n"

            with open(path, "a", encoding="utf8") as f:
                f.write(log)
            
            return result
        return wrapper
    return decorator